import React, { createContext, useContext, useState } from 'react';

interface User {
  id: string;
  username: string;
  email: string;
  avatar?: string;
}

interface AuthContextType {
  user: User | null;
  isLoggedIn: boolean;
  loading: boolean;
  error: string | null;
  login: (email: string, password: string) => void;
  register: (username: string, email: string, password: string) => void;
  logout: () => void;
  socialLogin: (provider: string) => void;
  clearError: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const login = (email: string, password: string) => {
    setLoading(true);
    setTimeout(() => {
      const mockUser = {
        id: '1',
        username: 'TestUser',
        email,
        avatar: 'https://mui.com/static/images/avatar/1.jpg',
      };
      setUser(mockUser);
      setLoading(false);
    }, 1000);
  };

  const register = (username: string, email: string, password: string) => {
    setLoading(true);
    setTimeout(() => {
      const mockUser = {
        id: '1',
        username,
        email,
        avatar: 'https://mui.com/static/images/avatar/1.jpg',
      };
      setUser(mockUser);
      setLoading(false);
    }, 1000);
  };

  const logout = () => {
    setUser(null);
  };

  const socialLogin = (provider: string) => {
    setLoading(true);
    setTimeout(() => {
      const mockUser = {
        id: '1',
        username: `${provider}User`,
        email: `${provider.toLowerCase()}@example.com`,
        avatar: 'https://mui.com/static/images/avatar/1.jpg',
      };
      setUser(mockUser);
      setLoading(false);
    }, 1000);
  };

  const clearError = () => setError(null);

  return (
    <AuthContext.Provider
      value={{
        user,
        isLoggedIn: !!user,
        loading,
        error,
        login,
        register,
        logout,
        socialLogin,
        clearError,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
